package manager.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import manager.actionform.ManagerForm;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import dao.ManagerMagDao;
import dao.impl.ManagerMagImpl;
import domain.Manager;

/**
 * 管理员管理个人信息（查看，修改）
 * 
 * May 13, 2009
 *
 * @author Fabian
 *
 */
public class ManagerSelfInfoAction extends DispatchAction {
	/**
	 *查看管理员个人信息
	 */
	public ActionForward show(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		//获取Session中的Manager的id
		HttpSession session = request.getSession();
		Manager mgr = null;
		mgr = (Manager)session.getAttribute("user");
		String jsonStr = "";
		if (mgr != null) {
			//组装返回的json数据
			jsonStr = jsonStr + "{root: [{id: " + mgr.getId() + ", name: '" + mgr.getName() +
								"', sex: '" + mgr.getSex() + "', nickname: '" + mgr.getNickname() +
								"', password: '" + mgr.getPassword() + "'}]}";
		}
		request.setAttribute("result", jsonStr);
		
		return mapping.findForward("show_result");
	}
	
	/**
	 * 获取管理员个人信息，返回，用于修改个人信息
	 */
	public ActionForward get(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		//获取Session中的Manager的id
		HttpSession session = request.getSession();
		Manager mgr = null;
		mgr = (Manager)session.getAttribute("user");
		
		//组装返回的JSON数据
		String jsonStr = "";
		
		if (mgr != null) {
			jsonStr = jsonStr + "{id: " + mgr.getId() + ", name: '" + mgr.getName() +
			"', sex: '" + mgr.getSex() + "', nickname: '" + mgr.getNickname() +
			"', password: '" + mgr.getPassword() + "'}";
		}
		
		request.setAttribute("result", jsonStr);
		
		return mapping.findForward("get_result");
	}
	
	/**
	 * 修改管理员个人信息 
	 */
	public ActionForward modify(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ManagerForm mf = (ManagerForm)form;
		Manager mgr = new Manager();
		mgr.setId(mf.getId());
		mgr.setName(mf.getName());
		mgr.setSex(mf.getSex());
		mgr.setNickname(mf.getNickname());
		mgr.setPassword(mf.getPassword());
		
		ManagerMagDao mmf = new ManagerMagImpl();
		boolean result = mmf.modifyManager(mgr);
		
		//组装返回的JSON数据
		String returnStr = "";
		if (result) {
			
			returnStr = "{success: true, msg: '恭喜，个人信息修改成功！请重新登陆！'}";
			request.setAttribute("result", returnStr);
			
		} else {
			
			returnStr = "{success: false, msg: '抱歉，个人信息修改失败！请重新尝试！'}";
			request.setAttribute("result", returnStr);
			
		}	
		return mapping.findForward("modify_result");
	}
}
